package Ptolemaiosz;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferStrategy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import javax.swing.*;

public class View extends Component{
	private LevelGraphicalEntity levelGraphycalEntity;
	private float FPS;
        private Controller controller;
        
        public static int width = 1000;
        public static int height = 600;
        
         //Modell
        //Referencia az application objektumra, hogy tugyjunk vele kommunikalni
        static Application application = null;  
        static Initializer initializer = null; 


	public void paint(Graphics graphics) {
		levelGraphycalEntity.draw(graphics);
                drawFPS(graphics);
	}

	public void setLevelGraphicalEntity(LevelGraphicalEntity levelGraphicalEntity) {
		levelGraphycalEntity=levelGraphicalEntity;
	}

        //osztaly a nevjegy felepitesere
        static class SimpleAboutDialog extends JDialog {
		  public SimpleAboutDialog(JFrame parent) {
			super(parent, "Névjegy", true);

			Box b = Box.createVerticalBox();
			b.add(new JLabel("Készítették:"));
			b.add(Box.createGlue());
			b.add(new JLabel("Biri Mátyás"));
			b.add(new JLabel("Délceg Máté"));
			b.add(new JLabel("Fodor Tamás"));
			b.add(new JLabel("Sári László"));
			b.add(new JLabel("Stefán Attila"));

			b.add(Box.createGlue());
			getContentPane().add(b, "Center");

			JPanel p2 = new JPanel();
			JButton ok = new JButton("Ok");
			p2.add(ok);
			getContentPane().add(p2, "South");

			ok.addActionListener(new ActionListener() {
			  public void actionPerformed(ActionEvent evt) {
				setVisible(false);
			  }
			});

			setSize(210, 190);
		  }
	}

	private void initialize() {

                 controller=new Controller();
                 controller.setApplication(application);
	         JFrame f = new JFrame("Ptolemaiosz");               
                 //f.setAutoRequestFocus(true);

                 //ablakot rendesen bezárja
                 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                 //listenerek
                 KeyListener listener = new KeyListener() {
                    @Override
                    public void keyPressed(KeyEvent e) {
                    controller.handleKeyPressed(e.getKeyChar());
                    
                     }

                    public void keyTyped(KeyEvent e) {
                    }

                    public void keyReleased(KeyEvent e) {
                    }
                };

            f.addKeyListener(listener);

                 //Menüsor a screenshothoz
		 JMenu menu=new JMenu("Fájl");
		 JMenuBar menubar=new JMenuBar();
		 JMenuItem menuitem1=new JMenuItem("Játék újrakezdése");
		 JMenuItem menuitem2=new JMenuItem("Kilépés");
		 JMenuItem menuitem3=new JMenuItem("Névjegy");
		 menubar.add(menu);
		 menu.add(menuitem1);
		 menu.add(menuitem3);
		 menu.add(menuitem2);
		 f.setJMenuBar(menubar);

                 //fajl torlese, es elso palyatol ujrakezdese a jateknek
		 menuitem1.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				File f=new File("level.sav");
				f.delete();
				initializer.loadLevel(1);
                        }
                });

                //kilepes menupont
		menuitem2.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				System.exit(0);
			}
                });

                //nevjegy dialogusablak megjelenitese
		menuitem3.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				JDialog f = new SimpleAboutDialog(new JFrame());
				f.setLocation(250,250);
				f.show();
			}
                });

                f.addWindowListener(new WindowAdapter(){
                    public void windowClosing(WindowEvent e) {
                    System.exit(0);
                    }
                });

                
                f.add(this);
                f.pack();
                f.setVisible(true);

                f.createBufferStrategy(2);

                //frissítes az ido telesenek fuggvényeben
                long lastTime = System.currentTimeMillis();
                while(true){
                try {
                    long currentTime = System.currentTimeMillis();
                    long deltaTime = currentTime - lastTime;

                    application.getPhysics().update((int) (deltaTime) );

                        //Calculate fps
                            if((deltaTime) != 0)
                                FPS =  (int) (1000 / deltaTime);

                        //upgrade last time
                        lastTime = currentTime;

                    BufferStrategy bf = f.getBufferStrategy();
                    Graphics canvas = bf.getDrawGraphics();

                    //Ellenorizzuk, hogy valtozott-e az ablak merete
                    if(f.getWidth() != View.width || f.getHeight() != View.height)
                        {
                            //Beallitjuk az uj dimenziokat
                            View.width  = f.getWidth() - 15;  //korrigacio a menu dimenziojaval
                            View.height = f.getHeight() - 60; //korrigacio a menu dimenziojaval
                            
                            //Ujra kell generalni a viewportokat
                            levelGraphycalEntity.recalculateViewPorts();
                        }
                    
                    f.paint(canvas);
                    canvas.dispose();

                    // Shows the contents of the backbuffer on the screen.
                    bf.show();
                    //Tell the System to do the Drawing now, otherwise it can take a few extra ms until
                    Toolkit.getDefaultToolkit().sync();
            } catch (Exception ex) {
            }
            }
    }

            public void drawFPS(Graphics g2) {
                g2.setColor(Color.red);
                g2.drawString("FPS: " + Float.toString(FPS), 10, 20);
            }
            
            //Ablak meretenek beallitasa
    public Dimension getPreferredSize() {
           
           return new Dimension(View.width, View.height);
    }
            
            
       public static void main(String[] args) {
        
        //Modell
            //Application letrehozasa
            application = new Application();
            
            //Initializer letrehozasa aki ismeri az applicationt
            initializer = new Initializer();
            initializer.setApplication(application);
            
            //Uj levelpartmanager, s megtanitas az applicationnak
            application.setLevelPartManager(new LevelPartManager());
            //Uj Initilaizer, s megtanitas az applicationnak
            application.setInitializer(initializer);
            //Uj Physics, s megtanitas az applicationnak
            application.setPhysics(new Physics());

          

            int loadlevel;
			//legutoljara jatszott palya szamat beolvasasa fajlbol
            try
            {
			FileInputStream fileIn = new FileInputStream("level.sav");
			ObjectInputStream in = new ObjectInputStream(fileIn);
			loadlevel = (Integer) in.readObject();
			in.close();
			fileIn.close();
            //ha nem talalta a fajlt, akkor az -es palyat allitja be az aktualisnak
            }catch(FileNotFoundException f){
			loadlevel=1;
            }catch(IOException i){
			i.printStackTrace();
			return;
            }catch(ClassNotFoundException c){
			c.printStackTrace();
			return;
            }
            
                //Modell vege
            TextureManager.loadTexture();
            View view = new View();
            
            initializer.view = view;
            application.getLevelPartManager().view = view;
            
            //betölti a loadlevel valtozo szerinti palyat
            initializer.loadLevel(loadlevel);
            
            LevelGraphicalEntity l = new LevelGraphicalEntity();
            l.setLevel(application.getLevelPartManager().getLevel());
             view.setLevelGraphicalEntity(l);
             
            view.initialize();   

    
       }
}